<template>
  <el-form label-width="100px">
    <el-form-item label="SPU名称">
      <el-input v-model="SpuParams.spuName" placeholder="请输入SPU名称"></el-input>
    </el-form-item>
    <el-form-item label="SPU品牌">
      <el-select v-model="SpuParams.tmId" placeholder="请选择SPU品牌" style="width: 25%">
        <el-option
          v-for="(item, index) in allTradeMark"
          :key="item.id"
          :label="item.tmName"
          :value="item.id"
        ></el-option>
      </el-select>
    </el-form-item>
    <el-form-item label="SPU描述">
      <el-input
        v-model="SpuParams.description"
        type="textarea"
        placeholder="请输入SPU描述"
      ></el-input>
    </el-form-item>
    <el-form-item label="SPU图标">
      <el-upload
        v-model:file-list="imgList"
        action="/api/admin/product/fileUpload"
        :http-request="customUpload"
        list-type="picture-card"
        :on-preview="handlePictureCardPreview"
        :before-upload="handlerBeforeUpload"
      >
        <el-icon>
          <Plus />
        </el-icon>
      </el-upload>
      <el-dialog v-model="dialogVisible">
        <img w-full :src="dialogImageUrl" alt="Preview Image" />
      </el-dialog>
    </el-form-item>
    <el-form-item label="SPU销售属性">
      <el-select
        v-model="saleAttrIdAndValueName"
        clearable
        :placeholder="unSelectSaleAttr.length ? `还有${unSelectSaleAttr.length}个未选择` : '无'"
        style="width: 20%"
      >
        <el-option
          v-for="(item, index) in unSelectSaleAttr"
          :key="item.id"
          :label="item.name"
          :value="`${item.id}:#:${item.name}`"
        ></el-option>
      </el-select>
      <el-button
        :disabled="saleAttrIdAndValueName ? false : true"
        style="margin-left: 10px"
        type="primary"
        size="default"
        icon="Plus"
        @click="addSaleAttr"
      >
        添加属性
      </el-button>
      <el-table
        v-if="hasSaleAttr"
        border
        style="margin: 10px 0px"
        :data="hasSaleAttr"
      >
        <el-table-column
          type="index"
          label="序号"
          width="80px"
          align="center"
        ></el-table-column>
        <el-table-column
          label="销售属性名字"
          width="200px"
          align="center"
          prop="saleAttrName"
        ></el-table-column>
        <el-table-column label="销售属性值">
          <template #default="{ row, $index }">
            <el-tag
              v-for="(item, index) in row.spuSaleAttrValueList"
              :key="item.id"
              style="margin: 0px 5px"
              closable
              @close="row.spuSaleAttrValueList.splice(index, 1)"
            >
              {{ item.saleAttrValueName }}
            </el-tag>
            <el-input
              v-if="row.flag == true"
              v-model="row.saleAttrValue"
              placeholder="请输入属性值"
              size="small"
              style="width: 100px"
              @blur="toLook(row)"
            ></el-input>
            <el-button
              v-else
              type="primary"
              size="small"
              icon="Plus"
              @click="toEdit(row)"
            ></el-button>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="150px" align="center">
          <template #default="{ row, $index }">
            <el-popconfirm
              :title="`确定删除销售属性【${row.saleAttrName}】吗?`"
              @confirm="hasSaleAttr.splice($index, 1)"
            >
              <template #reference>
                <el-button type="danger" size="small" icon="Delete"></el-button>
              </template>
            </el-popconfirm>
          </template>
        </el-table-column>
      </el-table>
    </el-form-item>
    <el-form-item>
      <el-button type="primary" size="default" @click="save">
        保存
      </el-button>
      <el-button size="default" @click="cancel">
        取消
      </el-button>
    </el-form-item>
  </el-form>
</template>

<script setup lang="ts">
const $emit = defineEmits(['changeScene'])
import { ref, computed } from 'vue'
import { ElMessage } from 'element-plus'
import type {
  SpuData,
  AllTradeMark,
  SpuHasImg,
  HasSaleAttrResponseData,
  AllSaleAttrResponseData,
  TradeMark,
  SpuImg,
  HasSaleAttr,
  AllSaleAttr
} from '@/api/product/spu/type'
import {
  reqAllTradeMark,
  reqAllSaleAttr,
  reqSpuHasSaleAttr,
  reqSpuImageList,
  reqAddOrUpdateSpu
} from '@/api/product/spu'


const customUpload = (options:any) => {
  const formData = new FormData()
  formData.append('file', options.file)

  // 创建 XMLHttpRequest 对象
  const xhr = new XMLHttpRequest()
  xhr.open(options.method, options.action, true)

  // 设置请求头
  xhr.setRequestHeader('TOKEN', localStorage.getItem('TOKEN') || '') // 示例：设置认证令牌

  xhr.onload = function() {
    if (xhr.status === 200) {
      options.onSuccess(JSON.parse(xhr.responseText)) // 调用 onSuccess 处理函数
    } else {
      options.onError() // 调用 onError 处理函数
    }
  }
  xhr.send(formData)
}


//子组件点击取消按钮，通知父组件切换场景为0，展示已有的SPU数据
const cancel = () => {
  $emit('changeScene', { flag: 0, params: 'update' })
}

//存储SPU对象
const SpuParams = ref<SpuData>({
  spuName: '',
  description: '',
  category3Id: '',
  tmId: '',
  spuSaleAttrList: [],
  spuImageList: []
})

//将来收集还未选择的SPU销售属性ID和名字
const saleAttrIdAndValueName = ref<string>('')

const allTradeMark = ref<TradeMark[]>([])
const imgList = ref<SpuImg[]>([])
const hasSaleAttr = ref<HasSaleAttr[]>([])
const allSaleAttr = ref<AllSaleAttr[]>([])

//更新已有的SPU初始化请求的方法，需要暴漏以供父组件调用
const initHasSpuData = async (spu: SpuData) => {
  //清空数据
  imgList.value = []
  hasSaleAttr.value = []
  saleAttrIdAndValueName.value = ''

  SpuParams.value = spu

  //spu即为父组件传递过来的已有的SPU对象【不完整】
  //获取全部品牌数据
  const result: AllTradeMark = await reqAllTradeMark()

  //获取某个品牌旗下的全部售卖商品图片
  const result1: SpuHasImg = await reqSpuImageList(spu.id as number)

  //获取已有的SPU销售属性的数据
  const result2: HasSaleAttrResponseData = await reqSpuHasSaleAttr(spu.id as number)

  //获取整个项目全部SPU的销售属性
  const result3: AllSaleAttrResponseData = await reqAllSaleAttr()

  //存储数据
  allTradeMark.value = result.data
  imgList.value = result1.data.map((item) => {
    return {
      name: item.imgName,
      url: item.imgUrl
    }
  })
  hasSaleAttr.value = result2.data
  allSaleAttr.value = result3.data

  //
  // SpuParams.value.spuImageList = imgList.value
  // SpuParams.value.spuSaleAttrList = hasSaleAttr.value
}

//添加一个新的SPU初始化请求的方法，需要暴漏以供父组件调用
const initAddSpu = async (c3Id: number | string) => {
  //清空数据
  Object.assign(SpuParams.value, {
    spuName: '',
    description: '',
    category3Id: '',
    tmId: '',
    spuSaleAttrList: [],
    spuImageList: []
  })
  imgList.value = []
  hasSaleAttr.value = []
  saleAttrIdAndValueName.value = ''

  SpuParams.value.category3Id = c3Id
  //获取全部品牌数据
  const result: AllTradeMark = await reqAllTradeMark()
  //获取整个项目全部SPU的销售属性
  const result1: AllSaleAttrResponseData = await reqAllSaleAttr()
  allTradeMark.value = result.data
  allSaleAttr.value = result1.data
}

const dialogImageUrl = ref<string>('')
const dialogVisible = ref<boolean>(false)

//照片墙点击预览按钮触发的钩子
const handlePictureCardPreview = (uploadFile: any) => {
  dialogImageUrl.value = uploadFile.url
  dialogVisible.value = true
}

//照片墙点击删除图片触发的钩子
// const handleRemove = () => {}

//照片墙上传成功之前的钩子，用来约束文件的大小和类型
const handlerBeforeUpload = (file: any) => {
  if (file.type != 'image/png' && file.type != 'image/jpeg' && file.type != 'image/gif') {
    ElMessage.error('上传图片的格式必须为png、jpeg或gif')
    return false
  } else if (file.size / 1024 / 1024 > 2) {
    ElMessage.error('上传图片不能大于2MB!')
    return false
  } else {
    return true
  }
}

//计算出当前SPU还未拥有的销售属性
const unSelectSaleAttr = computed(() => {
  const unSelectArr = allSaleAttr.value.filter((item) => {
    return hasSaleAttr.value.every((item1) => {
      return item.name != item1.saleAttrName
    })
  })
  return unSelectArr
})

//添加销售属性的方法
const addSaleAttr = () => {
  // baseSaleAttrId: number
  // saleAttrName: string
  // spuSaleAttrValueList: HasSpuSaleAttrValueList
  const [baseSaleAttrId, saleAttrName] = saleAttrIdAndValueName.value.split(':#:')

  //准备一个新的销售属性对象：将来带给服务器即可
  const newSaleAttr: HasSaleAttr = { baseSaleAttrId: Number(baseSaleAttrId as string), saleAttrName: saleAttrName as string, spuSaleAttrValueList: [] }
  //追加到已有的后面
  hasSaleAttr.value.push(newSaleAttr)
  saleAttrIdAndValueName.value = ''
}

//属性值按钮的点击事件
const toEdit = (row: HasSaleAttr) => {
  row.flag = true
  row.saleAttrValue = ''
}

//input元素失去焦点的回调
const toLook = (row: HasSaleAttr) => {
  const { baseSaleAttrId, saleAttrValue } = row
  if (saleAttrValue?.trim() == '') {
    ElMessage.error('添加的属性值不能为空')
    return
  }

  const repeat = row.spuSaleAttrValueList.find((item) => {
    return item.saleAttrValueName.trim() == saleAttrValue?.trim()
  })
  if (repeat) {
    ElMessage.error('添加的属性值不能重复')
    return
  }


  row.spuSaleAttrValueList.push({
    baseSaleAttrId,
    saleAttrValueName: saleAttrValue as string
  })
  row.flag = false
}

//保存按钮的回调
const save = async () => {
  //整理数据
  SpuParams.value.spuImageList = imgList.value.map((item: any) => {
    return {
      imgName: item.name,
      imgUrl: (item.response && item.response.data) || item.url
    }
  })
  SpuParams.value.spuSaleAttrList = hasSaleAttr.value
  //发请求
  const result = await reqAddOrUpdateSpu(SpuParams.value)
  if (result.code == 200) {
    ElMessage({
      type: 'success',
      message: SpuParams.value.id ? '更新成功！' : '添加成功！'
    })
    // 通知父组件切换场景为0，展示已有的SPU数据
    $emit('changeScene', { flag: 0, params: SpuParams.value.id ? 'update' : 'add' })
  } else {
    ElMessage({
      type: 'error',
      message: SpuParams.value.id ? '更新失败！' : '添加失败！'
    })
  }
}

//对外暴漏方法
defineExpose({ initHasSpuData, initAddSpu })
</script>

<style lang="scss" scoped></style>
